package com.zf.springdoc.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 1. 拿 token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            // 没登录 -> 直接返回 401，不放行
            //response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //return false;
            log.info("token is empty");
        }

        // 2. 解析 token，把用户信息放进 ThreadLocal，后面 Controller 随时拿
        UserContext.setUserId(1L);
        return true;   // true 才继续往后走
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        // 3. 请求结束记得清理 ThreadLocal，防止内存泄漏
        UserContext.clear();
    }
}